import SessionUtil, { JxbHttpClient } from "../../../data/session/session"
import PagePromoterUtil, { PagePromoter } from "../../../data/common/pagePromoter";
import AppSceneUtil from "../../../data/common/appScene"
const Common = require('../../../utils/common.js');
let pageSize = getApp().data.pageSize1;
Page({
  data: {
    token: '',
    ItemList: {},
    by_volume: '',
    by_volumes: '../../images/sp_05.png',
    by_price: '',
    by_prices: '../../images/sp_05.png',
    productsList: {},
    chosenNum: 1,
    pageNo: 1,
    name: '',
    Type: '',
    categoryId: '',
    flavorId: '',
    purposeId: '',
    priceRangeId: '',
    isloading: true,
    nomore: false,
    moretext: "加载更多",
    singleStock: "",
    has_Filter: false,
    has_Filters: '../../images/sp_07.png',
    isShowShoppingchart: false,
    isShowChartChange: false,
    productMaskClass: "",
    tagValues: 0,
    Details: true,
  },
  onLoad: function (options) {
    getApp().getSaleMode()
    PagePromoterUtil.showShareMenu().then()
    // 页面初始化 options为页面跳转所带来的参数
    SessionUtil.getInstance().then(session => {
      AppSceneUtil.setPageScene(this)
      let name = wx.getStorageSync('tagValue'),
          userid = session.getTheSessionUserSync().userId;
      this.setData({
        userid: userid
      })
      if (name) {
        this.setData({
          name: name
        });
      }
      // 品牌街
      let brand_id = options.brand_id;
      this.getBrandDetail(brand_id);
      this.setData({
        pageNo: 1,
        ItemList: {},
        tagValues: 0,
        brandId: brand_id
      });
      wx.setNavigationBarTitle({
        title: session.getTheSellingServerSync().getTheAgentSync().showName + '酒库',
      })
      let Filter = wx.getStorageSync('Filter');
      if (Filter) {
        this.setData({
          categoryId: Filter.categoryId,
          flavorId: Filter.flavorId,
          purposeId: Filter.purposeId,
          priceRangeId: Filter.priceRangeId,
        });
        const { categoryId, flavorId, purposeId, priceRangeId } = this.data
        if (categoryId || flavorId || purposeId || priceRangeId) {
          this.setData({
            has_Filter: true,
            has_Filters: '../../images/sp_08.png'
          });
        } else {
          this.setData({
            has_Filter: false,
            has_Filters: '../../images/sp_07.png'
          });
        }
      }
      this.ItemList();
    })
  },
  onShow: function () {
    SessionUtil.getInstance().then(session => {
      this.setData({
        tagValues: this.data.tagValues + 1,
      });
      let name = wx.getStorageSync('tagValue'),
          userid = session.getTheSessionUserSync().userId
      this.setData({
        userid: userid
      })

      if (this.data.tagValues <= 1 || name) {
        if (this.data.Details) {
          this.setData({
            name: name ? name : '',
            pageNo: 1,
            ItemList: {},
          });
          if (name) {
            this.setData({
              tagValues: 0,
            });
          }
          this.ItemList();
        } else {
          this.setData({
            Details: true,
            tagValues: 0,
          });
        }
      }
      let if_refresh = wx.getStorageSync("if_refresh");
      if (if_refresh == 5) {
        wx.removeStorageSync("Filter");
        this.setData({
          name: "",
          pageNo: 1,
          Type: "",
          categoryId: "",
          flavorId: "",
          purposeId: "",
          priceRangeId: "",
          specialString: "",
          by_volumes: '../../images/sp_05.png',
          by_prices: '../../images/sp_05.png',
          has_Filters: '../../images/sp_07.png',
        })
        this.ItemList();
      }
      //加载购物车
      this.productsLists();
    })

  },
  onHide: function () {
    wx.removeStorageSync("tagvalue");
    this.setData({
      isShowChartChange: false
    })
  },
  onUnload: function () {
    wx.removeStorageSync("Filter");
  },
  updateSearchKey: function (e) {
    if (e.detail.value) {
      this.setData({
        name: e.detail.value
      })
    }
  },
  goCarts: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/index'
    })
  },
  getBrandDetail: function (id) {
    let client = new JxbHttpClient();
    client.get({
      url: '/AppMaster/BrandInfo/brandDetail',
      data: {
        brand_id: id
      }
    }).then(jxbResp => {
      this.setData({
        brandDetail: jxbResp.data
      })
    })
  },

  /**关闭加入购物车弹窗 */
  hideCartpop: function (e) {
    this.setData({
      isShowChartChange: false
    })
  },

  //客服按钮阻止冒泡
  preventBubble(){
    return false;
  },

  // 更新搜索关键词
  goSearch: function (e) {
    this.setData({
      pageNo: 1,
      tagValues: 0,
    })
    wx.setStorageSync('tagValue', this.data.name);
    this.ItemList();
  },
  ItemList: function (action = '') {
    // 产品列表
    wx.showLoading({
      title: '数据加载中',
    })
    var page = this;
    var nowData = this.data.ItemList;
    var newData = {};
    var pageNo = this.data.pageNo;
    var name = this.data.name;
    var Type = this.data.Type;
    var categoryId = this.data.categoryId;
    var flavorId = this.data.flavorId;
    var purposeId = this.data.purposeId;
    var priceRangeId = this.data.priceRangeId;
    this.setData({
      isloading: false,
      moretext: "加载更多",
      nomore: true
    });
    //加载购物车
    this.productsLists();
    console.log(pageNo)
    if (pageNo < 1) {
      this.setData({
        isloading: true,
        nomore: false,
        moretext: "没有更多了"
      });
      wx.hideLoading();
      return;
    }
    
    let client = new JxbHttpClient();
    client.get({
      url: '/AppMaster/Item/ItemList',
      data: {
        pageSize: pageSize,
        pageNo: pageNo,
        name: name,
        type: Type,
        categoryId: categoryId,
        flavorId: flavorId,
        purposeId: purposeId,
        priceRangeId: priceRangeId,
        brandId: page.data.brandId
      }
    }).then(jxbResp => {
      pageNo++;
      let Lists = jxbResp.data.list;
      if (Lists.length) {
        newData = Lists;
      } else {
        pageNo = -100;
        this.setData({
          isloading: true,
          nomore: false,
          moretext: "没有更多了"
        });
      }
      if (action == 'Refresh') {
        console.log('is Refresh!');
        this.productsLists();
        wx.stopPullDownRefresh();
      } else if (action == 'Page') {
        console.log('is Page!');
        if (nowData.length) {
          var newData = nowData.concat(Lists)
        } else {
          var newData = Lists
        }
      }
      this.setData({
        ItemList: newData,
        pageNo: pageNo,
        isloading: true,
        nomore: false,
      });
      // 关闭加载
      wx.hideLoading();
    }).catch(err=>{
      console.log(err);
    })
  },
  onPullDownRefresh: function () {
    var page = this;
    page.setData({
      ItemList: {},
      pageNo: 1
    });
    page.ItemList('Refresh');
    wx.stopPullDownRefresh();
  },
  onReachBottom: function () {
    var pageNo = this.data.pageNo;
    this.setData({
      pageNo: pageNo
    });
    this.ItemList('Page');
  },
  OrderBy: function (e) {
    // console.log(e);
    // console.log(e.currentTarget.id);
    var page = this;
    var ID = e.currentTarget.id;
    var by_volume = page.data.by_volume;
    var by_price = page.data.by_price;

    /*
        序规则:
        1 = 销量顺序
        2 = 销量倒序
        3 = 单价顺序
        4 = 单价倒序
        0 = 默认
    */

    if (ID == 'volume') {
      console.log('volume');
      if (by_volume == '') {
        page.setData({
          by_volume: 'down',
          by_volumes: '../../images/sp_02.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 2
        });
      } else if (by_volume == 'down') {
        page.setData({
          by_volume: 'up',
          by_volumes: '../../images/sp_03.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 1
        });
      } else if (by_volume == 'up') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 0
        });
      }
    } else if (ID == 'price') {
      console.log('price');
      if (by_price == '') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: 'down',
          by_prices: '../../images/sp_02.png',
          Type: 4
        });
      } else if (by_price == 'down') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: 'up',
          by_prices: '../../images/sp_03.png',
          Type: 3
        });
      } else if (by_price == 'up') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 0
        });
      }
    }

    page.setData({
      pageNo: 1
    });

    page.ItemList();

  },
  goDetail: function (e) {
    var itemId = e.currentTarget.id;
    this.setData({
      Details: false,
    })
    wx.navigateTo({
      url: '/pages/product/detail/detail?itemId=' + itemId
    })
  },
  cancelCart: function () {
    var page = this;
    var isShowChartChange = page.data.isShowChartChange;
    var bIsisShowChartChange = isShowChartChange ? false : true;
    page.setData({
      isShowChartChange: bIsisShowChartChange,
      productMaskClass: bIsisShowChartChange ? "product-mask" : "",
    });
  },
  goFilter: function () {
    var page = this;
    wx.navigateTo({
      url: '/pages/product/filter/filter'
    })
  },
  AddCart: function (e) {
    this.productsLists();
    var ID = e.currentTarget.id
    var itemId = ID.split('-')[0];
    var stock = ID.split('-')[1];
    var chosenItem;
    var insideNum = 0;
    var thisStock;
    var thislist;
    var acartid;
    this.setData({
      list_year: 0
    })
    // 显示年份
    let client = new JxbHttpClient()
    client.get({
      url: '/AppMaster/Item/getItemYearsList',
      data: {
        item_id: itemId
      }
    }).then(jxbResp => {
      var normalInfo = jxbResp.data.item_info;
        var list_year = jxbResp.data.item_year_list;
        var activity = normalInfo.activity_category;
        if (activity != 0) {
          activity = activity.split(",");
        }
        this.setData({
          chosenItem: normalInfo,
          list_year: list_year,
          activity: activity
        })
    })

    this.setData({
      isShowChartChange: true,
      chosenNum: 1,
      singleStock: thisStock,
      sitemId: itemId,
      oldNum: insideNum,
      thisCartid: acartid
    });
  },
  // 点击年份切换商品
  changeYear: function (e) {
    var page = this;
    var itemId = e.currentTarget.id;
    var list_year = page.data.list_year;
    var chosenItem = page.data.chosenItem;
    if (chosenItem.item_id == itemId) {
      return false;
    } else {
      console.log(list_year)
      for (var i = 0; i < list_year.length; i++) {
        if (itemId == list_year[i].item_id) {
          var activity = list_year[i].activity_category;
          if (activity != 0) {
            activity = activity.split(",");
          }
          page.setData({
            chosenItem: list_year[i],
            sitemId: itemId,
            activity: activity
          })
        }
      }
    }
  },

  goCart: function () {
    let num = this.data.chosenNum;//输入框的数量
    num = parseInt(num);
    (new JxbHttpClient()).post({
      url: '/AppMaster/PosCart/PosAddCart',
      data: {
        number: num,
        itemId: this.data.sitemId
      }
    }).then(jxbResp=>{
      console.log(jxbResp)
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000
      })
      this.productsLists();
      this.cancelCart();
      this.setData({
        chosenNum: 0
      })
    }).catch(err=>{
      console.log(err)
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  reduceSingle: function () {
    var page = this;
    var num = page.data.chosenNum - 1;
    if (num <= 1) {
      page.setData({
        chosenNum: 1,
      })
    } else {
      page.setData({
        chosenNum: num,
      })
    }
  },
  addToCartSingle: function () {
    var page = this;
    var stock = page.data.singleStock;
    var num = page.data.chosenNum + 1;
    if (num >= stock) {
      wx.showToast({
        title: '库存不足！',
        image: '../../images/fail.png',
        duration: 2000
      })
    } else {
      page.setData({
        chosenNum: num,
      })
    }
  },
  toZero: function (e) {
    var num = e.detail.value;
    if (num.length == 0) {
      this.setData({
        chosenNum: 1
      })
    }
  },
  updateNum: function (e) {
    var num = e.detail.value;
    var tnum = parseInt(num);
    this.setData({
      chosenNum: tnum
    })
  },

  productsLists: function () {
    (new JxbHttpClient()).get('/AppMaster/PosCart/cartDetail').then(jxbResp =>{
      let respData = jxbResp.data;
      var products = respData.productsList;
      var total = 0, gross = 0.00;
      var list = respData.activity_list
      var itemids = [];
      var limits = [];
      for (var z = 0; z < list.length; z++) {
        if (list[z].activity_category == 6) {
          itemids = itemids.concat(list[z].itemids);
        }
        if (list[z].activity_category == 4) {
          limits = limits.concat(list[z].itemids);
        }
      }
      for (var i = 0; i < products.length; i++) {
        total = total + products[i].carNumber;
        gross = gross + products[i].carNumber * products[i].show_price;
        var z = Common.contains(itemids, products[i].itemid),
          w = Common.contains(limits, products[i].itemid);
        if (z && w) {
          products[i].activity_list = ['秒杀', '限购']
        } else {
          if (z) {
            products[i].activity_list = ['秒杀'];
          }
          if (w) {
            products[i].activity_list = ['限购'];
          }
        }
      }
      respData.total = total;
      respData.gross = gross.toFixed(2);
      respData.productsList = products;
      this.setData({
        productsList: respData,
      })
    }).catch(err => {
      console.log(err)
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
      this.setData({
        productMaskClass: "",
        productsList: {},
      })
    })
  },
  shoppingChartList: function () {
    var page = this;
    var isShowShoppingchart = page.data.isShowShoppingchart;

    var bIsShowShoppingchart = isShowShoppingchart ? false : true;
    page.setData({
      isShowChartChange: false,
      isShowShoppingchart: bIsShowShoppingchart,
      productMaskClass: bIsShowShoppingchart ? "product-mask" : ""
    })
  },

  shoppingCartAdd: function (e) {
    let itemId = parseInt(e.currentTarget.id);
    (new JxbHttpClient()).post({
      url: '/AppMaster/PosCart/PosAddCart', 
      data: {
        number: 1,
        itemId: itemId
      }
    }).then(jxbResp=>{
      this.productsLists();
    }).catch(err=>{
      console.log(err)
      wx.showToast({
        title: err.message,
        image: '../../images/fail.png',
        duration: 2000
      })
    })
  },

  shoppingCartReduce: function (e) {
    var itemId = e.currentTarget.id;
    var cartId = itemId.split('_')[0];
    var num = itemId.split('_')[1] - 1;
    if (num < 1) {
      (new JxbHttpClient()).post({
        url: '/AppMaster/PosCart/PosDelete', 
        data: {
          cartId: cartId
        }
      }).then(jxbResp=>{
        this.productsLists();
      }).catch(err=>{
        console.log(err)
      })
    } else {
      (new JxbHttpClient()).post({
        url: '/AppMaster/PosCart/PosUpdate',
        data: {
          number: num,
          cartId: cartId
        },
      }).then(jxbResp=>{
        this.productsLists();
      }).catch(err=>{
        console.log(err)
      })
    }
  },
  clearShoppingCart: function (e) {
    var page = this;
    (new JxbHttpClient()).post('/AppMaster/PosCart/PosDelMyCart').then(jxbResp=>{
      this.setData({
        productsList: [],
        isShowShoppingchart: !this.data.isShowShoppingchart,
        productMaskClass: '',
      })
      wx.showToast({
        title: '购物车已清空',
        icon: 'success',
        duration: 2000
      })
    }).catch(err=>{
      console.log(err)
    })
  },
  goOrderConfirm: function () {
    var _this = this
    _this.productsLists();
    setTimeout(function () {
      if (!_this.data.productsList.productsList) {
        Common.Alert("提示", "请先添加购物车!");
      } else {
        _this.clearStorageSync();
        var userid = _this.data.userid;
        if (userid < 0) {
          wx.navigateTo({
            url: '/pages/my/logintype/logintype?from=0'
          });
        } else {
          wx.navigateTo({
            url: '/pages/product/orderConfirm/index'
          });
        }
      }
    }, 500);
  },
  onShareAppMessage: function(){
    let session = SessionUtil.getInstanceSync(),
    resp = (new PagePromoter( this.route, {}))
    .setShareTitle(session.getTheSellingServerSync().showName)
    .buildShareInfo() 
    console.log(resp, '分享内容')
    return resp
  },
  clearStorageSync: function () {
    wx.setStorageSync("dilivery", '');
    wx.setStorageSync("invoice", {});
    wx.setStorageSync("pay", {});
  },
})